import { Body, Controller, Get, Logger, Param, Post, Put, Query, Req } from '@nestjs/common'
import { AuthService } from './auth.service'
import RegisterDto from './dto/register.dto'
import LoginDto from './dto/login.dto'
import { HttpService } from '@nestjs/axios'
import { catchError, map } from 'rxjs/operators'
import { firstValueFrom } from 'rxjs'
import { UpdateAuthDto } from '@/auth/dto/update-auth-dto'
import { Auth } from '@/decorators'
import { Request } from 'express'
@Controller('auth')
export class AuthController {
  constructor(private auth: AuthService, private httpService: HttpService) {}

  @Post('login')
  login(@Body() dto: LoginDto) {
    return this.auth.login(dto)
  }
  @Get('userInfo')
  @Auth()
  userInfo(@Req() req: Request) {
    // @ts-ignoreS
    const id = Number(req.user.id)
    return this.auth.userInfo(id)
  }
  @Put()
  @Auth()
  update(@Req() req: Request, @Body() UpdateAuthDto: UpdateAuthDto) {
    // @ts-ignoreS
    const id = Number(req.user.id)
    return this.auth.update(id, UpdateAuthDto)
  }
  @Post('register')
  register(@Body() dto: RegisterDto) {
    return this.auth.register(dto)
  }
  @Get('weapp/userinfo')
  async getUserInfo(@Query('code') code: string) {
    console.log(code)
    const appid = 'wx2dd18106dc9b03d7'
    const secret = 'fbeb8e6bc79b985d2f87386f0347c8d8'
    const { data } = await firstValueFrom(
      this.httpService
        .get(
          `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code `,
        )
        .pipe(),
    )
    return data
    // const data = await this.httpService
    //   .get(
    //     `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code `,
    //   )
    //   .pipe(map((response) => response))
    //   .toPromise()
    // console.log(data)
    // try {
    //   const { openid, session_key } = await this.wechatOAuthService.getSessionByCode(code)
    //   // 处理登录逻辑，例如将用户信息存储到数据库中
    //   // 返回用户信息，例如 openid 和 session_key
    //   return { openid, session_key }
    // } catch (err) {
    //   Logger.error(err)
    //   throw err
    // }
    return 111
  }
}
